package cn.lxh.controller.app;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.lxh.constants.Constants;
import cn.lxh.pojo.domain.PayOrder;
import cn.lxh.result.JSONResult;
import cn.lxh.service.IPayOrderService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lxh Create Time: 2024/1/16 23:52
 */
@Tag(name = "支付",description = "支付")
@RestController
@RequestMapping("/app/pay")
public class AppPayController {

    @Autowired
    public IPayOrderService payOrderService;


    @Operation( summary= "微信支付",description = "微信支付")
    @Parameter(name = "orderNo",description = "订单号",required = true)
    @PostMapping("/wechatPay/{orderNo}")
    public JSONResult wechatPay(@PathVariable String orderNo){
        return JSONResult.success(payOrderService.wechatPay(orderNo));
    }

    @Operation( summary= "支付结果查询",description = "支付结果查询")
    @Parameter(name = "orderNo",description = "订单号",required = true)
    @GetMapping("/payResult/{orderNo}")
    public JSONResult payResult(@PathVariable String orderNo){

        PayOrder payOrder = payOrderService.getOne(new LambdaQueryWrapper<PayOrder>()
                .eq(PayOrder::getOrderNo, orderNo)
                .eq(PayOrder::getPayStatus, Constants.PAY.STATUS_SUCCESS_PAY));

        return JSONResult.success(payOrder);
    }


    @Operation( summary= "微信支付异步回调",description = "微信支付异步回调")
    @PostMapping("/wechatPayNotify")
    @SaIgnore
    public JSONResult wechatPayNotify(HttpServletRequest request, HttpServletResponse response){
        try {
            payOrderService.wechatPayNotify(request);
            // 返回200, 微信不再回调
            response.setStatus(HttpStatus.OK.value());
        }catch (Exception e){
            e.printStackTrace();
            // 返回500, 微信还会回调
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
        return JSONResult.success();
    }

    //异步回调
    @Operation( summary= "小程序微信分账异步回调",description = "小程序微信分账异步回调")
    @PostMapping("/wxmp/shardingNotify")
    @SaIgnore
    public JSONResult wxmpShardingNotify(HttpServletRequest request, HttpServletResponse response){
        try {
            payOrderService.wxmpShardingNotify(request);
            //返回200 ， 微信不再回调
            response.setStatus(HttpStatus.OK.value());
        }catch (Exception e){
            e.printStackTrace();
            //返回500 ，微信还会回调
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
        return JSONResult.success();
    }
}
